package com.panopset.flywheel;

import java.util.Stack;
import java.util.Vector;

/**
 * Flywheel static utility methods.
 *
 * @author Karl Dinwiddie
 */
final class Util {

    /**
     * Given a Vector of commands, tie the quit commands to the
     * MatchableCommands.
     *
     * @param commands
     *            Commands to add structure to.
     * @return New Vector of commands.
     * @throws Exception
     *             Exception is thrown if there is an unmatched quit.
     */
    protected static Vector<Command> matchQuitCommands(
            final Vector<Command> commands) throws Exception {
        final Vector<Command> rtn = new Vector<Command>();
        final Stack<MatchableCommand> stack = new Stack<MatchableCommand>();
        for (Command command : commands) {
            if (stack.isEmpty()) {
                if (!(command instanceof MatchableCommand)) {
                    rtn.add(command);
                }
            } else {
                stack.peek().getCommands().add(command);
            }
            if (command instanceof MatchableCommand) {
                if (stack.isEmpty() || command instanceof CommandFile) {
                    rtn.add((MatchableCommand) command);
                }
                stack.push((MatchableCommand) command);
            } else if (command instanceof CommandQuit) {
                if (stack.isEmpty()) {
                    throw new Exception("Un-matched quit found, stopping.");
                } else {
                    stack.pop();
                }
            }
        }
        return rtn;
    }

    /**
     * Prevent instantiation.
     */
    private Util() {
    }
}
